package com.magicborrow.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    /**
     * 通过拼接的方式构造请求内容，实现参数传输以及文件传输
     *
     * @param url
     * Service net address
     * @param params
     * text content
     * @param files
     * pictures
     * @return String result of Service response
     * @throws IOException
     */
    public static final double MAX_LEANTH = 100 * 1024;


    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用数据装
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        // 关闭流一定要记得。
        return outstream.toByteArray();
    }


    public static String post(String url, Map<String, String> params,
                              Map<String, File> files, String fileKey) throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);
    /*	String token = "YG.USFood.ANDROID.AAAAB3NzaC1yc2EAAAABIwAAAQEAwEtF1hfvsOpIboYO01g1D0ZOVPm1p";
		String timestamp = System.currentTimeMillis() + "";
		Random rd = new Random();
		int ad = rd.nextInt(10000);
		String nonce = ad + "";
		String[] columns = new String[] { token, timestamp, nonce };
		Arrays.sort(columns);
		String singature = VolleyTool.convertSHA1(TextUtils.join("", columns));
		conn.setRequestProperty("YgUsFood", "signature=" + singature + "&timestamp="
				+ timestamp + "&nonce=" + nonce);*/

        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // 发送文件数据
        if (files != null&&files.size()!=0)
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);

                sb1.append("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\""
                        + file.getValue().getName() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINEND);
                // sb1.append("Content-Type: application/octet-stream;" +
                // LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(file.getValue().getPath(), options);
                Bitmap bmp = null;
                options.inJustDecodeBounds = false;
                long b = file.getValue().length();
                Log.i("file_length", "" + file.getValue().length());
                if (b > 500 * 1024) {
                    options.inSampleSize = (int) (b / (500 * 1024));
                    bmp = BitmapFactory.decodeFile(file.getValue().getPath(), options);
                } else {
                    bmp = BitmapFactory.decodeFile(file.getValue().getPath());
                }
//                System.out.println("path:"+file.getValue().getPath());
//                bmp=BitmapUtils.getHttpBitmap(file.getValue().getPath());

//                bmp=BitmapFactory.decodeStream(new FileInputStream(file.getValue()));
                //   Log.i("bmp_length", "" + bmp.get);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                Log.i("bmp====>", "" + baos.toByteArray().length);
                InputStream is = new ByteArrayInputStream(baos.toByteArray());

                //System.out.println("is");
                byte[] buffer = new byte[1024];
                int len = 0;
                int i = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                    //System.out.println("ttttt====="+(i++));

                }
                is.close();
                outStream.write(LINEND.getBytes());
            }

        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 得到响应码
        int res = conn.getResponseCode();
        Log.i("==res==", "" + res);
        StringBuilder sb2 = new StringBuilder();
        InputStream in = conn.getInputStream();

        if (res == 200) {
            int ch;
            while ((ch = in.read()) != -1) {
                sb2.append((char) ch);
            }
        }
        outStream.close();
        conn.disconnect();
        String yo = conn.getContentEncoding();
        String txt = new String(sb2.toString().getBytes("iso8859-1"), "utf-8");
        return txt;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                //	System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            //System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    private static ByteArrayInputStream compressImage(File file) {
        Bitmap image = BitmapFactory.decodeFile(file.getPath());
        //ImageUtil.calculateZoomSize(width, height, reqWidth, reqHeight)


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream isBm = null;
        if (file.length() < MAX_LEANTH) {

            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        } else {


            double f = file.length();
            int d = (int) (f / MAX_LEANTH);


            // bitmapZoomByScale(image,Math.sqrt(d))
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = false;
            newOpts.inSampleSize = d;
            //System.out.println("d======"+d);
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
            try {
                baos.close();
                baos.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            //System.out.println("=============="+bitmap.getByteCount());
            try {
                isBm.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            isBm = null;
            isBm = new ByteArrayInputStream(baos.toByteArray());

        }

        return isBm;
    }

    public interface HttpRequestListener {
        void httpError();

        void httpSuccess(String msg);
    }

}